package com.thornBird.think.notepad.dao;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.util.Assert;

import com.thornBird.think.notepad.entity.BaseEntity;
import com.thornBird.think.notepad.util.ReflectionUtils;

public class BaseDao<T extends BaseEntity> {
	
	private Logger logger = LoggerFactory.getLogger(BaseDao.class);
	
	@Resource(name = "hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	protected Class<T> entityClass;
	
	public BaseDao() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
	}

	public void save(T entity) {
		Assert.notNull(entity, "Entity can not be null.");
		entity.setCreateTime(new Date());
		hibernateTemplate.save(entity);
		logger.debug("Save entity: {}", entity);
	}
	
	public void update(T entity) {
		Assert.notNull(entity, "Entity can not be null.");
		entity.setUpdateTime(new Date());
		hibernateTemplate.update(entity);
		logger.debug("Update entity: {}", entity);
	}
	
	public void unavailable(long id) {
		Assert.notNull(id, "Id can not be null.");
		T entity = find(id);
		Assert.notNull(entity, "Entity can not be null.");
		if (entity.isAvailable()) {
			entity.setAvailable(false);
			entity.setUpdateTime(new Date());
			hibernateTemplate.update(entity);
			logger.debug("Unavailable entity: {}", entity);
		}
	}
	
	public void available(long id) {
		Assert.notNull(id, "Id can not be null.");
		T entity = find(id);
		Assert.notNull(entity, "Entity can not be null.");
		if (!entity.isAvailable()) {
			entity.setAvailable(true);
			entity.setUpdateTime(new Date());
			hibernateTemplate.update(entity);
			logger.debug("Available entity: {}", entity);
		}
	}
	
	public void delete(T entity) {
		Assert.notNull(entity, "Entity can not be null.");
		hibernateTemplate.delete(entity);
		logger.debug("Delete entity: {}", entity);
	}
	
	public T find(long id) {
		Assert.notNull(id, "Id can not be null.");
		return (T) hibernateTemplate.load(entityClass, id);
	}

}
